
import axios from "axios"
import { Loading, Message } from 'element-ui';
import router from "@/router"

// let baseURL = "http://localhost:3000/"  本地IP
let baseURL = "http://101.200.120.23:3000/" 
 

//请求的基路径
axios.defaults.baseURL = baseURL
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let load = null
export function showLoading() {
    load && load.close();
    load = Loading.service({
        lock: true,      //锁住遮罩层
        text: '请求中....',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
    });
}

export function showSuccess(msg) {
    msg = msg || "请求成功"
    load && load.close();
    Message.success({
        message: msg,
        center: true
    })
}

export function showError(msg) {
    msg = msg || "请求失败"
    load && load.close();
    Message.error({
        message: msg,
        center: true,
        showClose: true,   //关闭按钮
        duration: 1200     //限时
    })
}



// Interceptors 拦截器 
//  请求发送之前的拦截器 
axios.interceptors.request.use(function (config) {
    // 请求发送之前做的事情 
    console.log(config);
    // 把token 带到请求头里，每次请求ajax都会默认带着token
    var token = sessionStorage.getItem("token")
    if (token) {
        config.headers['token'] = token
    }
    showLoading()
    return config;
}, function (error) {
    // 请求发送失败 
    showError('请求发送失败');
    return Promise.reject(error);
});


// 响应结束之前的拦截器 
axios.interceptors.response.use(function (response) {
    // 状态码判断 
    // 打印 返回的数据 
    console.log(response.data)  // axios 的数据存在data 
    setTimeout(() => {
        if (response.data.type) {
            showSuccess(response.data.msg);
        } else {
            if (response.data.type == 0) {
                showError(response.data.msg);
            } else {
                showSuccess(response.data.msg);
            }
        }
    }, 500)

if(response.data.code == "3200"){
    // token 有问题  重新登陆
    router.push({name:'login'})
}


    return response;
}, function (error) {
    // 响应失败 
    showError('响应失败')
    return Promise.reject(error);
});


export const get = (url, params) => {
    return new Promise(function (resolve, reject) {
        axios.get(url, {
            params
        })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}

export const post = (url, params) => {
    return new Promise(function (resolve, reject) {
        axios.post(url, params)
            .then(res => {
                resolve(res.data)    //res.data
            })
            .catch(err => {
                reject(err)
            })
    })
}



export { axios ,baseURL}